#include"../inc/hal.h"
#include"../inc/arg.h"
#include"../inc/tty.h"

__xdata char tty_buf[TTY_BUF_MAX];
__bit uart1_idle;
char *uart1_bpt;
__code char digit[]="0123456789ABCDEF";

void tty_init(unsigned int baud){
	SCON = 0x50;
	AUXR |= 0x40;
	AUXR &= 0xFE;
	TMOD &= 0x0F;
	TL1 = (char)baud;
	TH1 = (char)(baud >> 8);
	ET1 = 0;
	TR1 = 1;

    uart1_idle = 1;
}

void tty_write(char *str){
    uart1_bpt = str;
    while(TI);
    SBUF = *uart1_bpt++;
    uart1_idle = 0;
}

bool tty_idle(void){
    return uart1_idle;
}

void uart1_isr(void) __interrupt(4){
    if(TI){
        TI = 0;
        if(*uart1_bpt){
            SBUF = *uart1_bpt++;
        }
        else{
            uart1_idle = 1;
        }
    }
    if(RI){
        RI = 0;
    }
}

//unsigned int convert to string
//return next ptr
char *utostr(unsigned int num,char *str){
    char *ptr;
    unsigned char i=0,j;

    do{
        str[i++]=digit[num % 10];
        num /= 10;
    }while(num);
    //????倒序


    while(num/)
}
char *itostr(int num,char *str);
char *ftostr(float num,char *str,char prec);

//format as %[prec(only for float)][type:d/u/f/l/x/c/s]
int vsprintf(char *buf,char *fmt,va_list){
    //??
}
int sprintf(char *buf,char *fmt,...){
    va_list args;
    int n;

    va_start(args,fmt);
    n = vsprintf(buf,fmt,args);
    va_end(args);

    return n;
}

int printf(const char* fmt,...){
    va_list args;
    int n;

    va_start(args,fmt);
    n = vsprintf(tty_buf,fmt,args);
    va_end(args);
    tty_write(tty_buf);

    return n;
}